//
//  NYVersionManager.m
//  NOAHWM
//
//  Created by Ryan on 13-7-4.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "NYVersionManager.h"
#import "JSON.h"

@implementation NYVersionManager

#pragma mark - Singleton methods

+ (NYVersionManager *)sharedManager
{
    static NYVersionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NYVersionManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [super dealloc];
}

#pragma mark - Public methods

- (void)checkVersion
{
    NSString *suburl = kGetAppVersionUrl;
    suburl = [suburl stringByAppendingString:@"app000056"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
        NSString *serverVersion = [dict objectForKey:@"appVersion"];
        if(![serverVersion isEqualToString:localVersion])
        {
            UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"升级提醒" message:@"微诺亚有新版本，是否马上升级？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"升级", nil] autorelease];
            [av show];
        }
        else
        {
            UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"微诺亚已是最新版本，无须升级。" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
            [av show];
        }
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UIAlertViewDelegate methods
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:kAppDownloadUrl,kAppAppleId]]];
    }
}

@end
